package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author zsk
 * @create 2022-03-01-11:26
 */
@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    //查询分类列表
    @Override
    public List<Category> findAll() {
        //调用mapper层查询并返回
        return categoryMapper.findAll();
    }

    //新增菜品分类
    @Override
    public void save(Category category) {
        //补全参数
        //雪花算法生成id
        category.setId(IdUtil.getSnowflake(1, 1).nextId());

//        category.setCreateTime(new Date());
////        category.setUpdateTime(new Date());
////        category.setCreateUser(1L);
////        category.setUpdateUser(1L);//todo 临时写死

        //调用mapper层添加
        categoryMapper.save(category);
    }

    //修改菜品分类信息
    @Override
    public void update(Category category) {
        //设置修改人与修改时间
//        category.setUpdateUser(1L);//todo 临时写死
//        category.setUpdateTime(new Date());//todo 临时写死

        //调用mapper层修改
        categoryMapper.updateById(category);
    }

    //删除菜品分类信息
    @Override
    public ResultInfo deleteById(Long id) {
        //调用mapper层查询当前菜品分类下菜品数量
        Integer count = categoryMapper.contDishByCategoryId(id);
        if (count > 0) {
            throw new CustomException("当前分类下存在菜品,不允许删除");
        }

        //调用mapper层查询当前分类下套餐数据
        Integer count1 = categoryMapper.countSetmealCategoryId(id);
        if (count1 > 0){
            throw new CustomException("当前分类下存在套餐，不允许删除");
        }

        //都通过之后根据id允许删除
        categoryMapper.deleteById(id);

        //返回成功标识
        return ResultInfo.success(null);

    }

    @Override
    public List<Category> findByType(Integer type) {

        //设置查询条件
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        //where type = #{type}
        wrapper.eq(Category::getType,type);

        //调用mapper层查询
        return categoryMapper.selectList(wrapper);

    }
}
